package ming.hello.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import ming.hello.entry.User;
import ming.hello.service.UserService;
import ming.hello.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController extends BaseController{

    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtils redis;

    @RequestMapping("/selectAll")
    @ResponseBody
    public List<User> selectAll(){
        return userService.selectAll();
    }

    @RequestMapping("/selectAll2")
    @ResponseBody
    public List<User> selectAll2(){
        if (redis.get("user") != null) {
            String str = redis.get("user").toString();
            logger.info("12345566778"+ str);
            JSONObject jsonObject = JSONObject.parseObject(str);
            List<User> list = jsonObject.getJSONArray("user").toJavaList(User.class);
            logger.info("获取缓存信息user:{}", list.toString());
            return list;
        }
        List<User> list = userService.selectAll2();
        Map<String, Object> map = new HashMap<>();
        map.put("user", list);
        redis.set("user", JSON.toJSONString(map));
        logger.info("UserController#selectAll2#List<User>:{}", JSON.toJSONString(list));
        return list;
    }

    @RequestMapping("/selectAll3")
    @ResponseBody
    public List<User> selectAll3(){
        //集合转化为jsonc串然后放入redis中，取出来的时候直接转为字符串，最后通过JSON.parseArray解析成集合
        if (redis.get("user") != null) {
            String str = (String) redis.get("user");
            logger.info("1111111111111111111111111"+ str);

            List<User> list = JSON.parseArray(str, User.class);
            logger.info("获取缓存信息user:{}", list.toString());
            return list;
        }
        List<User> list = userService.selectAll2();
        redis.set("user", JSON.toJSONString(list));
        logger.info("UserController#selectAll2#List<User>:{}", JSON.toJSONString(list));
        return list;
    }

    @RequestMapping("/query")
    @ResponseBody
    public List<User> query(){
        Map<String, Object> map = new HashMap<>();
        List<String> userlist = new ArrayList<>();
        userlist.add("Lily");
        userlist.add("jamy");
        userlist.add("song");
        map.put("userList", userlist);
        List<User> list2 = userService.query(map);
        return list2;
    }

    @ResponseBody
    @RequestMapping("/save")
    public void save(){
        userService.save();
    }
}
